package com.lhb.controller;

import com.lhb.dao.Repository.UserRepository;
import com.lhb.pojo.BaseResp;
import com.lhb.pojo.User;
import com.lhb.pojo.rep.UserReq;
import com.lhb.pojo.rep.UserRoleReq;
import com.lhb.service.UserService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;

/**
 * @author LiangHaiBo
 * @version 1.0
 * @date 2021.10.11 下午 19:36
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    UserService userService;

    @RequiresPermissions(value = {"SYSTEM_ROLE_AUTH"})
    @RequestMapping(value = "/findAll", method = RequestMethod.GET)
    public BaseResp findAll(@RequestParam("page") Integer page, @RequestParam("limit") Integer limit) {
        BaseResp all = userService.findAll(page, limit);
        return all;
    }

    @RequestMapping("/del")
    public void delete(@RequestParam("id") Integer id) {
        userService.deleteById(id);
    }

    @RequestMapping("/login")
    public BaseResp login(@RequestBody UserReq userReq, HttpServletRequest request) {
        return userService.login(userReq, request);
    }

    @RequestMapping("/getUser")
    public BaseResp getUser(HttpServletRequest request) {
        HttpSession session = request.getSession();
        Object user = session.getAttribute("user");
        if (user != null) {
            return new BaseResp(0, "已登录", null, user);
        }
        return new BaseResp(1, "未登录", null, null);
    }

    @RequestMapping("/logOut")
    public BaseResp logOut(HttpServletRequest request) {
        HttpSession session = request.getSession();
        Object user = session.getAttribute("user");
        if (user != null) {
            session.removeAttribute("user");
            return new BaseResp(0, "退出成功", null, user);
        }
        return new BaseResp(1, "未登录", null, null);
    }

    @RequestMapping("/sendMail")
    public BaseResp sendMail(@RequestBody Map map, HttpSession session) {
        return userService.sendMail(map.get("userName"), session);
    }


    @RequestMapping("/insertUser")
    public BaseResp insertUser(@RequestBody UserReq userReq, HttpSession session) {
        return userService.insertUser(userReq, session);
    }


    @RequestMapping("/updateUser")
    public BaseResp updateUser(@RequestBody User user) {
        System.out.println(user);
        return userService.updateUser(user);
    }

    @RequestMapping("updateRole")
    public BaseResp updateRole(@RequestBody UserRoleReq req) {
        return userService.updateRole(req);

    }


}
